package com.waidi.clothespad.websocket;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.util.Log;
import android.content.Context;

import java.io.File;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;


import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;

import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONArray;


import com.waidi.clothespad.common.Config;
import com.waidi.clothespad.common.MessageToUi;
import com.waidi.clothespad.common.Qccxzjlxt;
import com.waidi.clothespad.common.RealData;

import org.json.JSONException;
import org.json.JSONObject;
import com.waidi.clothespad.common.Db;
import com.waidi.clothespad.common.WorkerInfo;

/**
 * Created by ll on 2017/12/18.
 */

public class MyWebsocketClient extends WebSocketClient{

    private static final String TAG = MyWebsocketClient.class.getSimpleName();
    private static String websocketHost;
    public boolean conn = false;
    public Context context;
    public File image_dir;
    public Handler handler;
    public Handler handler1;

    public Handler gxlxt_handler =null;


    public static Handler handler2;
    public Db myDbHelper = null;

    public int heatout = 0;
    public String devid= "1";
    public static String videourlfile;

    public MyWebsocketClient( URI serverUri , Draft draft ) {
        super( serverUri, draft );
    }

    public MyWebsocketClient( URI serverURI ) {
        super( serverURI );
        websocketHost = serverURI.toString();
        Log.i(TAG,"new WebsocketClient obj..." );
    }

    @Override
    public void onOpen( ServerHandshake handshakedata ) {
       // System.out.println( "opened connectioned  ............."+ websocketHost);
        Log.i(TAG,"opened connectioned  ............."+ websocketHost);
        // if you plan to refuse connection based on ip or httpfields overload: onWebsocketHandshakeReceivedAsClient
        conn =true;
        try {
            JSONObject login = new JSONObject();
            login.put("action","client.login");
            JSONObject data = new JSONObject();
            data.put("devid",Config.qrcode);
            String locaton=Config.qrCodeInfo.location;
            data.put("location", locaton);
            login.put("data",data);
            send(login.toString());
            Log.i(TAG,login.toString());


            if(Config.rfidWorkerInfo.workernum.length()==0)
                return;

            JSONObject workinfosync = new JSONObject();
            workinfosync.put("action", "timer.workerinfo.sync");
            JSONObject data1 = new JSONObject();

            data.put("devid", Config.qrcode);
            String locaton1=Config.qrCodeInfo.location;
            data.put("location", locaton1);
            data.put("empcode", Config.rfidWorkerInfo.workernum);
            data.put("islogin", "1");

            workinfosync.put("data",data);
            send(workinfosync.toString());
            Log.i(TAG,workinfosync.toString());



            Bundle bundle0=new Bundle();
            bundle0.putString("websocket","net_connect");
            Message msg1;
            msg1=handler1.obtainMessage();//每发送一次都要重新获取
            msg1.setData(bundle0);
            msg1.arg1 = 1;
            handler1.sendMessage(msg1);//用handler向主线程发送信息
            heatout = 0;

/*            msg1=handler.obtainMessage();//每发送一次都要重新获取
            msg1.setData(bundle0);
            msg1.arg1 = 3;
            handler.sendMessage(msg1);//用handler向shishishuju_ui发送信息*/

        }catch (JSONException e)
        {
           // Toast.makeText(this, e.toString(),Toast.LENGTH_SHORT).show();
            Log.i(TAG,e.toString());

        }
    }

    @Override
    public void onMessage( String message ) {
        heatout = 0;
        new MessageToUi().send(1,"websocket","net_connect",handler1);

        System.out.println( "received: " + message );
        try {
            JSONObject jsonObj = new JSONObject(message);
            if(jsonObj==null)
                return;

            if(jsonObj.has("action")==true)
            {
                String action = jsonObj.optString("action");
                Log.i(TAG, action);

                if (action.compareTo("image.info") == 0) {
                    JSONObject jsonObj_image_data = jsonObj.optJSONObject("data");
                    String data_base64 = jsonObj_image_data.optString("image_data");
                    Log.i(TAG, "image_data: " + data_base64);
                    byte[] imageByte = Base64.decode(data_base64, Base64.DEFAULT);
                    Bitmap bitmap = BitmapFactory.decodeByteArray(imageByte, 0, imageByte.length);
                    File file = new File(image_dir + "/1" + ".jpg");
                    FileOutputStream out = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
                    out.flush();
                    out.close();
                    Log.i(TAG, file.toString());
                    Message msg;
                    Bundle bundle = new Bundle();
                    bundle.putString("image.info", file.toString());//bundle中也可以放序列化或包裹化的类对象数据
                    msg = handler.obtainMessage();//每发送一次都要重新获取
                    msg.setData(bundle);
                    msg.arg1 = 1;
                    handler.sendMessage(msg);//用handler向主线程发送信息
                }
                else if (action.compareTo("real.info") == 0) {
                    JSONObject jsonObj_realinfo_data = jsonObj.optJSONObject("data");
                    Bundle bundle1 = new Bundle();
                    RealData data = new RealData();
                    data.line_number = jsonObj_realinfo_data.optString("line_number");
                    data.work_station = jsonObj_realinfo_data.optString("work_station");
                    data.worker_id = jsonObj_realinfo_data.optString("worker_id");
                    data.worker_name = jsonObj_realinfo_data.optString("worker_name");
                    data.style_id = jsonObj_realinfo_data.optString("style_id");
                    data.style_size = jsonObj_realinfo_data.optString("style_size");
                    data.order_id = jsonObj_realinfo_data.optString("order_id");
                    data.lineproject = jsonObj_realinfo_data.optString("RouteName");

                    data.opera_code = jsonObj_realinfo_data.optString("opera_code");
                    data.opera_desc = jsonObj_realinfo_data.optString("opera_desc");
                    data.style_colour = jsonObj_realinfo_data.optString("style_colour");
                    bundle1.putParcelable("real.info", data);
                    Message msg1;
                    msg1 = handler.obtainMessage();//每发送一次都要重新获取
                    msg1.setData(bundle1);
                    msg1.arg1 = 2;
                    handler.sendMessage(msg1);//用handler向主线程发送信息

                    File gylxt = new File(Config.realinfotxt);
                    OutputStream os = new FileOutputStream(gylxt);
                    byte b[] = jsonObj.toString().getBytes("UTF-8");
                    os.write(b);
                    os.close();
                }
                else if (action.compareTo("heart.info") == 0) {
                    heatout = 0;
                    //reponse pong
                }
                else if (action.compareTo("dg.worker.info.update") == 0) {
                    heatout = 0;
                    JSONObject obj = jsonObj.optJSONObject("data");
                    String name = obj.optString("name");
                    String code = obj.optString("code");
                    String location = obj.optString("location");
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String t=format.format(new Date());

/*                    if(name.length()==0 || code.length()==0)
                        return;*/

                    Config.rfidWorkerInfo.workernum = code;
                    Config.rfidWorkerInfo.workername = name;
                    Config.rfidWorkerInfo.line = location;
                    Config.rfidWorkerInfo.logtime = t;


                    if(Config.rfidWorkerInfo.workernum.length()==0||
                            Config.rfidWorkerInfo.workername.length()==0)
                    {
                        Config.rfidWorkerInfo.workername = "未登录";
                        Config.rfidWorkerInfo.logtime = "0000-00-00 00:00:00";
                    }

                    Config.rfidworkerinfosave();

                    WorkerInfo tmp = new WorkerInfo();
                    tmp.name = name;
                    tmp.id = code;
                    tmp.line = location;
                    tmp.logontime = t;

                    new MessageToUi().sendParcelable(801,"dg.worker.info.update",tmp,handler1);
                    new MessageToUi().sendParcelable(801,"dg.worker.info.update",tmp,handler);

                }
                else if(action.compareTo("time.info")==0)
                {
                    JSONObject realtime = jsonObj.optJSONObject("data");
                    String time = realtime.optString("realtime");
                    Config.pctime = time ;

                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                    long millionSeconds = sdf.parse(time).getTime();//毫秒
                    Log.i(TAG,"时间戳: "+millionSeconds);
                }
                else if(action.compareTo("order.return") == 0)
                {
                    Log.i(TAG,"#"+jsonObj.toString());
                    JSONObject obj = jsonObj.optJSONObject("data");

                    String result =obj.optString("result");

                    if(result.compareTo("success")==0)
                        new MessageToUi().send(800,"order.return",result,handler);
                    if(result.compareTo("failed")==0) {
                        String msg = obj.optString("msg");
                        new MessageToUi().send(802, "order.return",msg , handler);
                    }
                    Log.i(TAG,"#"+result);
                }
                else if(action.compareTo("timer.order.return.cardNo") == 0)
                {
                    Log.i(TAG,"#"+jsonObj.toString());
                    JSONObject obj = jsonObj.optJSONObject("data");
                    String hangerid =obj.optString("cardno");
                    Config.globalrealhangerid = hangerid;
                    if(Config.fragShenglineqc!=null)
                    new MessageToUi().send(803, "timer.order.return.cardNo","" , Config.fragShenglineqc.handler);

                }
                else if (action.compareTo("qc.info") == 0) {
                    Log.i(TAG,jsonObj.toString());
                    String style_id = jsonObj.optString("style_id");
                    String order_id = jsonObj.optString("order_id");
                    String style_size = jsonObj.optString("style_size");
                    String style_colour = jsonObj.optString("style_colour");
                    String Order_Quantity = jsonObj.optString("order_quantity");

                    Config.qccxzjlxt.order_id = order_id;
                    Config.qccxzjlxt.style_id = style_id;
                    Config.qccxzjlxt.order_quantity = Order_Quantity;

                    Log.i(TAG, Config.qccxzjlxt.order_id + "-" + Config.qccxzjlxt.style_id + "-" + Config.qccxzjlxt.order_quantity);


                    JSONArray qcArray = jsonObj.getJSONArray("data");
                    if (qcArray == null)
                        return;
                    Config A = new Config(context);
                    Qccxzjlxt B = new Qccxzjlxt();
                    if (qcArray.length() != 0)
                        Config.qccxzjlxt.gxinfoArrayList.clear();
                    for (int i = 0; i < qcArray.length(); i++) {
                        JSONObject s = (JSONObject) qcArray.get(i);
                        Qccxzjlxt.gxinfo tmp = B.new gxinfo();
                        tmp.line_number = s.optString("line_number");
                        tmp.work_station = s.optString("work_station");
                        tmp.worker_id = s.optString("worker_id");
                        tmp.worker_name = s.optString("worker_name");
                        tmp.opera_desc = s.optString("opera_desc");
                        tmp.opera_code = s.getString("opera_code");
                        tmp.primary_order = s.optString("Primary_Order");
                        Config.qccxzjlxt.gxinfoArrayList.add(tmp);
                    }


                    File gylxt = new File(Config.gylxttxt);
                    OutputStream os = new FileOutputStream(gylxt);
                    byte b[] = jsonObj.toString().getBytes("UTF-8");
                    os.write(b);
                    os.close();

                    Bundle bundle2 = new Bundle();
                    bundle2.putString("gxlxt", "update");
                    Message msg1;

                    if (gxlxt_handler != null) {
                        msg1 = gxlxt_handler.obtainMessage();//每发送一次都要重新获取
                        msg1.setData(bundle2);
                        msg1.arg1 = 1;
                        Log.i(TAG, "send message ...");
                        gxlxt_handler.sendMessage(msg1);//用handler向主线程发送信息
                    }
                }

            }


        }catch (JSONException e)
        {
            Log.i(TAG,e.toString());
        }
        catch (ParseException n)
        {
            n.printStackTrace();
        }
        catch (FileNotFoundException s)
        {
                s.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    @Override
    public void onClose( int code, String reason, boolean remote ) {
        // The codecodes are documented in class org.java_websocket.framing.CloseFrame
        System.out.println( "Connection closed by " + ( remote ? "remote peer" : "us" ) + " Code: " + code + " Reason: " + reason );
        conn = false;
        Config.webscoekt_conn = false;
        Bundle bundle2=new Bundle();
        bundle2.putString("websocket","net_disconnect");
        Message msg1;
        msg1=handler1.obtainMessage();//每发送一次都要重新获取
        msg1.setData(bundle2);
        msg1.arg1 = 1;
        handler1.sendMessage(msg1);//用handler向主线程发送信息

/*        msg1=handler.obtainMessage();//每发送一次都要重新获取
        msg1.setData(bundle2);
        msg1.arg1 = 3;
        handler.sendMessage(msg1);//用handler向shishishuju_ui发送信息
        Log.i(TAG,"websocket disconnect!");*/
    }

    @Override
    public void onError( Exception ex ) {
        ex.printStackTrace();

        new MessageToUi().send(1,"websocket","net_disconnect",handler1);
       // new MessageToUi().send(3,"websocket","net_disconnect",handler);


        // if the error is fatal then onClose will be called additionally
        Log.i(TAG,"websocket ERROR");
        ex.printStackTrace();
        close(0);

    }

    //向数据库中插入和更新数据
    public void insertAndUpdateData(Db myHelper,RealData data){
      //获取数据库对象
        SQLiteDatabase db = myHelper.getWritableDatabase();
/*        //使用execSQL方法向表中插入数据
        db.execSQL("insert into hero_info(name,level) values('bb',0)");*/
        //使用insert方法向表中插入数据

        ContentValues values = new ContentValues();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
        String ptime = format.format(new Date()); //产生该条生产记录的时间
        values.put("ptime", ptime);
        values.put("orderid", data.order_id);
        values.put("styleid", data.style_id);
        values.put("style_size", data.style_size);
        values.put("style_color", data.style_colour);
        values.put("gx_code", data.opera_code);
        values.put("worker_name", data.worker_name);
        db.insert("Production_record", "ptime", values);
        values.clear();
        //关闭SQLiteDatabase对象
        db.close();
    }
}
